<?php


namespace common\plugins\editors\tinymce;

use Yii;
use yii\base\Behavior;
use yii\helpers\Url;

/**
 * description of ActionlogBehavior
 *
 * @author FireLoong
 */
class PluginBehavior extends Behavior
{
    public $options = [];
    public $form;
    public $inputId;

    public function editor()
    {
        $this->form->assets['editor'] = [
            'sourcePath' => '@common/plugins/editors/tinymce/media',
            'js' => ['tinymce.min.js'],
            'bundles' => ['yii\bootstrap\BootstrapThemeAsset', 'yii\bootstrap\BootstrapPluginAsset']
        ];

        if (isset($this->options['width']) && !empty($this->options['width'])) {
            if (!is_numeric($this->options['width']) && is_string($this->options['width'])) {
                $this->options['width'] = '\'' . $this->options['width'] . '\'';
            }
        } else {
            $this->options['width'] = '\'100%\'';
        }
        $this->options['height'] = $this->options['height'] ?? 500;

        $lang = str_replace('-', '_', Yii::$app->language);

        $imageList = Url::to(['/media/images/index','type'=>'tinymce','alt' => 1]);

        $js = <<<JS
tinymce.init({
    selector: '#$this->inputId',
    width: {$this->options['width']},
    height: {$this->options['height']},
    language: '$lang',
    plugins: [
        'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
        'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
        'save table directionality emoticons template paste help'
    ],
    toolbar: 'insertfile undo redo | styleselect | bold italic forecolor backcolor | alignleft aligncenter' +
     ' alignright alignjustify | bullist numlist outdent indent | link image media emoticons | preview fullscreen ' +
      '| print help',
    templates: [
        {title: 'some title 1', description: 'some desc 1', content: 'My Content 1'},
        {title: 'some title 2', description: 'some desc 2', content: 'My Content 2'}
    ],
    convert_urls: false,
    image_advtab: true,
    //image_uploadtab: true,
    images_upload_url: '$imageList',
    file_picker_types: 'image',
    file_picker_callback: function(callback, value, meta){
        if (meta.filetype == 'image'){
            tinymce.activeEditor.windowManager.openUrl({
                title: 'Insert image',
                url: '$imageList',
                onMessage: function(api,details) {
                  callback(details.data.url, details.data.objVals);
                  api.close();
                }
            });
        }
    }
});
JS;
        $this->form->view->registerJs($js);
    }
}
